/**
 * author:Administrator
 * date:2016/1/4
 * desc:TODO
 */

'use strict';

var Model = require('../model/couponUser.js');
var counter = require('./counter.js');
var myCounter = counter.bindCounter(counter.TypesEnum.couponUser);
var dao = {};

module.exports = dao;

dao.empty = function* () {
  return yield Model.remove({});
};

/**
 * 添加一个"空"的优惠券
 */
dao.addBlank = function*(uid, cvid) {
  var cuid = yield myCounter();
  var entity = new Model({
    cuid: cuid,
    uid: uid,
    cvid: cvid,
    qty: -1 // -1表示这个仅仅是个空的记录
  });
  return yield entity.save();
};

dao.findOne = function*(query) {
  return yield Model.findOne(query);
};

dao.remove = function*(query) {
  return yield Model.remove(query);
};

dao.findOneAndUpdate = function*(query, update, option) {
  return yield Model.findOneAndUpdate(query, update, option);
};

dao.transPhase_pending = function*(cuid, qty, tid) {
  return yield Model.findOneAndUpdate(
    {cuid: cuid, pendingTransactions: {$ne: tid}},
    {$set: {qty: qty}, $push: {pendingTransactions: tid}},
    {upsert: false, 'new': true}
  );
};

dao.transPhase_applied = function*(cuid, tid) {
  return yield Model.findOneAndUpdate(
    {cuid: cuid, pendingTransactions: {$all: tid}},
    {$pull: {pendingTransactions: tid}},
    {upsert: false, 'new': true}
  );
};